# 方法一：
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        n = len(nums)
        i, j = 0, k - 1
        ans = float("-inf")
        while j < n:
            total = 0
            for p in range(i, j + 1):
                total += nums[p]
            ans = max(ans, total)
            i += 1
            j += 1
        return ans / k

# 方法二
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        n = len(nums)
        i, j = 0, k - 1
        ans, total = float("-inf"), 0
        for p in range(k):
                total += nums[p]
        ans = max(ans, total)
        while j < n:
            total -= nums[i]
            i += 1
            j += 1
            if j == n:
                break
            total += nums[j]
            ans = max(ans, total)
        return ans / k

# 方法三
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        max_s = -inf  # 窗口元素和的最大值
        s = 0  # 维护窗口元素和
        for i, x in enumerate(nums):
            # 1. 进入窗口
            s += x
            if i < k - 1:  # 窗口大小不足 k
                continue
            # 2. 更新答案
            max_s = max(max_s, s)
            # 3. 离开窗口
            s -= nums[i - k + 1]
        return max_s / k
